const express = require('express');
const jiemi = require('../util/jiemi');
const jiami = require('../util/verifyCode');
const limiter= require('../util/rate_limit')
const connection = require('../util/db');
const dataForm=require('../util/dataForm');
var router = express.Router();
var verifyCode = '';
connection.connect();


/* GET home page. */
router.get('/', (req, res, next) => {
    verifyCode = req.query.c;
    res.end();
});
router.get('/checkRep', (req, res, next) => {
    // connection.connect();
    let sql='select * from '+dataForm.dataform+' where username='+req.query.username;
    console.log(req.query.username)
    connection.query(sql,(error,result)=>{
        if((result==null||result.length==0)){
            res.send({code:1,msg:'可以注册'})
            res.end();
        }else{
            res.send({code:0,msg:'用户名已存在'})
            res.end();
        }
    })
    // connection.end()
});
router.post('/', limiter,function (req, res) {
    let {vCode,code}=req.body;
    console.log('jiemi',jiemi(verifyCode))
    console.log('cosw',req.body.code)
    console.log('jiemi',req.body.vCode)


    if (code.toLowerCase() == jiemi(vCode).toLowerCase()) {
        // connection.connect();
        let sql = 'insert into '+dataForm.dataform+'(nickname,username,password) values(?,?,?)';
        let params = [req.body.nickname, req.body.username, req.body.password]
        connection.query(sql, params, (err, result) => {
            if (err) {
                console.log('[INSERT ERROR] - ', err.message);
                return;
            }
            res.send({code:200,msg:'注册成功'});
            res.end();
            console.log('--------------------------INSERT----------------------------');
            console.log('INSERT ID:', result);
            console.log('-----------------------------------------------------------------\n\n');
        });
        // connection.end();
    }else{
        res.send({code:403,msg:'请通正规方式注册'});
        res.end();
    }
});


module.exports = router;